import { createRouter,createWebHistory } from 'vue-router'
import Home from './views/Home.vue'
import Login from './views/Login.vue'
import ColumnDetail from './components/ColumnDetail.vue'
import CreatePost from './views/createPost.vue'
import store from './store'
import axios from 'axios'
import SignUp from './views/SignUp.vue'
import postDetail from './views/postDetail.vue'
import Edit from './views/Edit.vue'
const routerHistory = createWebHistory()
const router = createRouter({
    history:routerHistory,
    routes:[
        {
            path:'/',
            name:'home',
            component:Home
        },
        {
            path:'/login',
            name:'login',
            component:Login,
            meta:{
                redirectAlreadyLogin:true
            }
        },
        {
            path:'/column/:id',
            name:'column',
            component:ColumnDetail
        },
        {
            path:'/createPost',
            name:'createPost',
            component:CreatePost,
            meta:{
                requiredLogin:true
            }

        },
        {
          path: '/signup',
          name: 'signup',
          component: SignUp,
          meta: { redirectAlreadyLogin: true }
        },
        {
          path: '/postdetail/:id',
          name: 'postdetail',
          component: postDetail,
          
        },
        {
          path: '/edit/:id',
          name: 'edit',
          component: Edit,
          meta:{
            requiredLogin:true
          } 
        },
    ]
})
// 全局前置守卫，在路由跳转前进行判断
router.beforeEach((to,from,next)=>{
    // 从 store 中获取用户登录状态和 token
    const { user, token } = store.state
    // 获取目标路由的元信息
    const { requiredLogin, redirectAlreadyLogin } = to.meta
    console.log('Current user state:', user)
    console.log('Current token:', token)
    console.log('Route meta:', to.meta)
    // 如果用户未登录
    if (!user.isLogin) {
      // 但是有 token
      if (token) {
        // 设置请求头的 Authorization
        axios.defaults.headers.common.Authorization = `Bearer ${token}`
        // 获取当前用户信息
        store.dispatch('fetchCurrentUser').then(() => {
          // 如果是需要重定向已登录用户的页面(如登录页),则重定向到首页
          if (redirectAlreadyLogin) {
            next('/')
          } else {
            next()
          }
        }).catch(e => {
          // token 验证失败
          console.error(e)
          // 登出用户
          store.commit('logout')
          // 跳转到登录页
          next('login')
        })
      } else {
        // 如果没有 token,且页面需要登录
        if (requiredLogin) {
          // 跳转到登录页
          next('login')
        } else {
          next()
        }
      }
    } else {
      // 用户已登录,对于登录页等页面重定向到首页
      if (redirectAlreadyLogin) {
        next('/')
      } else {
        next()
      }
    }

})
export default router